//alert("Cinluding");
function replaceNextLine(field){
	return field.replace(/\n/,' ');
}

function checkMailId(mailId)
{
//
var arr = new Array(
'.com','.net','.org','.biz','.coop','.info','.museum','.name','.pro',
'.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag','.ai','.al',
'.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw','.az','.ba','.bb',
'.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm','.bn','.bo','.br','.bs',
'.bt','.bv','.bw','.by','.bz','.ca','.cc','.cd','.cf','.cg','.ch','.ci',
'.ck','.cl','.cm','.cn','.co','.cr','.cu','.cv','.cx','.cy','.cz','.de',
'.dj','.dk','.dm','.do','.dz','.ec','.ee','.eg','.eh','.er','.es','.et',
'.fi','.fj','.fk','.fm','.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh',
'.gi','.gl','.gm','.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy',
'.hk','.hm','.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io',
'.iq','.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
'.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li','.lk',
'.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg','.mh','.mk',
'.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt','.mu','.mv','.mw',
'.mx','.my','.mz','.na','.nc','.ne','.nf','.ng','.ni','.nl','.no','.np',
'.nr','.nu','.nz','.om','.pa','.pe','.pf','.pg','.ph','.pk','.pl','.pm',
'.pn','.pr','.ps','.pt','.pw','.py','.qa','.re','.ro','.rw','.ru','.sa',
'.sb','.sc','.sd','.se','.sg','.sh','.si','.sj','.sk','.sl','.sm','.sn',
'.so','.sr','.st','.sv','.sy','.sz','.tc','.td','.tf','.tg','.th','.tj',
'.tk','.tm','.tn','.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug',
'.uk','.um','.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu',
'.ws','.wf','.ye','.yt','.yu','.za','.zm','.zw');

var sd = mailId;
var ids = sd.split(",");
var val = true;

for(var j=0; j<ids.length; j++)
{
	var mai = ids[j];
	var dot = mai.lastIndexOf(".");
	var ext = mai.substring(dot,mai.length);
	var at = mai.indexOf("@");
	var dom = dot - at;
        var sp = mai.indexOf(" ");
	if(dom >= 4 && at > 1 && sp == -1)
	{
		for(var i=0; i<arr.length; i++)
		{
			if(ext == arr[i])
			{
			val = true;
			break;
			}
			else
			{
			val = false;
			}
		}
		if(val == false)
		{
			return false;
		}
	}
	else
	{	 
	 return false;
	}
}

return true;
}


/*
 * Function  : Trim
 * Description : This function  trims any string  
 *               value which has spaces embedded 
 *               in  them.
 * 
 */
function trim(str) {
	var i=0
	var ltrimstr = ""
	var rtrimstr = ""
	var nstr = ""

	l = str.length;
	for(i=0;i<l;i++) {
		if((str.charCodeAt(i)==13) || (str.charCodeAt(i)==10))
			nstr += ''
		else
			nstr += str.charAt(i)
	}

	l = nstr.length;
	for(i=0;i<l;i++) {
		if(nstr.charAt(i) != " ")
			break
	}
	ltrimstr = nstr.substring(i,l)
	l = ltrimstr.length;
	for(i=l-1;i>=0;i--) {
		if(ltrimstr.charAt(i) != " ")
			break
	}

	rtrimstr = ltrimstr.substring(0, i+1)
	return rtrimstr
}

/*
 * Function  : isInteger
 * Description : This function  checks if the  passed value is 
 *               an  integer.
 * 
 */
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

/*  Function : validateFieldLenght
 *  Description : check the lenght of the field
 */
 function validateFieldLenght(field,lengt)
 { 	
 	var isValidLength=true;
 	if(field.length>lengt)
 	{
 		isValidLength=false;
 		alert("Data exceed the valid range (size).\nPermissible data size for this column is "+lengt
 		      +" character.\nPlease enter data with permissible size,\nElse data may be truncated.");
 	}
 	return isValidLength;
 }
 
 //Added my mkk1kor , to submit the form while opening the pop up 
 
 /*
	 * Returns an new XMLHttpRequest object, or false if the browser doesn't
	 * support it
	 */
function newXMLHttpRequest() {

  var xmlreq = false;

  // Create XMLHttpRequest object in non-Microsoft browsers
  if (window.XMLHttpRequest) {
    xmlreq = new XMLHttpRequest();

  } else if (window.ActiveXObject) {

    try {
      // Try to create XMLHttpRequest in later versions
      // of Internet Explorer

      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
      
    } catch (e1) {

      // Failed to create required ActiveXObject
      
      try {
        // Try version supported by older versions
        // of Internet Explorer
      
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");

      } catch (e2) {

        // Unable to create an XMLHttpRequest by any means
        xmlreq = false;
      }
    }
  }

return xmlreq;
}
 /*
  * Returns a function that waits for the specified XMLHttpRequest
  * to complete, then passes it XML response to the given handler function.
  * req - The XMLHttpRequest whose state is changing
  * responseXmlHandler - Function to pass the XML response to
  */
 function getReadyStateHandler(req, responseXmlHandler) {

   // Return an anonymous function that listens to the XMLHttpRequest instance
   return function () {

     // If the request's status is "complete"
     if (req.readyState == 4) {

       // Check that we received a successful response from the server
       if (req.status == 200) {

         // Pass the request to the handler function.
         responseXmlHandler(req);

       } else if (req.status == 1000) {

			// problem has occurred with the file handling
			document.body.style.cursor="auto";
			alert(req.responseText);
       
	   } else {

         // An HTTP problem has occurred
         alert("HTTP error "+req.status+": "+req.statusText);
       }
     }
   }
 }
function clearSelectionBox(selectionBoxObj) {
	if(!(selectionBoxObj==null || selectionBoxObj.options == null)){
		var numberOfOptions = selectionBoxObj.options.length;
		// Empty select box
		// selectionBox.options.length = 0;
		for ( var k = 0; k < numberOfOptions; k++) {
			selectionBoxObj.remove(0);
		}
	}
}

function trimNbsp(strNbsp) 
{ 
	return strNbsp.replace(/^[\s(&nbsp;)]+/g,'').replace(/[\s(&nbsp;)]+$/g,''); 
}

function download(url,data,method)
{
	//url and data options required
	if( url && data ){ 
		//data can be string of parameters or array/object
		data = typeof data == 'string' ? data : jQuery.param(data);
		//split params into form inputs
		var inputs = '';
		jQuery.each(data.split('&'), function(){ 
			var pair = this.split('=');
			inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
		});
		//send request
		jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
		.appendTo('body').submit().remove();
	};
}

function padStr(i) {
    return (i < 10) ? "0" + i : "" + i;
}

function displayNiceDateFormat(date) {
	return '(' + $.datepicker.formatDate('dd-M-yy ', date) 
		+ padStr(date.getHours()) + ':'
		+ padStr(date.getMinutes()) + ':'
		+ padStr(date.getSeconds()) + ')';
}

//init global today string
var today = new Date();
var date = today.getDate().toString();
if (date.length == 1) {
	date = "0" + date;
}
var month = (today.getMonth() + 1).toString();
if (month.length == 1) {
	month = "0" + month;
}
todayStr = date + "." + month + "." + today.getFullYear();

function linkFormatter(cellValue, options, rowdata, action) 
{
	//var url = "http://rt-fabigate.rt.de.bosch.com:8777/iGate/stdReport?lotid=" + cellValue + "&report_at=" + todayStr + "&file=dlz_lotid.xml&dlz_target=0"
	var url = "http://rt-fabigate:8777/iGate/stdReport?file=dlz_lotid.xml&lotid=" + cellValue + "&report_at=" + todayStr + "&dlz_target=0";
	return "<a href=javascript:open_in_new_tab('" + url + "');>" + cellValue + "</a>";
}

function linkUnFormatter(cellValue, options, rowdata, action) 
{
    return cellValue;
}
function open_in_new_tab(url) {
	window.open(url, '_blank');
	window.focus();
}
function printDate(date) {
	var dateStr = '';
	if (date != null) {
		dateStr = padStr(date.getFullYear()) + '-' +
                  padStr(1 + date.getMonth()) + '-' +
                  padStr(date.getDate());
	}
    return dateStr;
}

function copyToClipboardCrossbrowser(s) {           

    if( window.clipboardData && clipboardData.setData )
    {
        clipboardData.setData("Text", s);
    }           
    else
    {
        // You have to sign the code to enable this or allow the action in about:config by changing
        //user_pref("signed.applets.codebase_principal_support", true);
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

        var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;

        // create a transferable

        var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;

        // specify the data we wish to handle. Plaintext in this case.
        trans.addDataFlavor('text/unicode');

        // To get the data from the transferable we need two new objects
        var str = new Object();
        var len = new Object();

        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

        str.data= s;        

        trans.setTransferData("text/unicode",str, str.data.length * 2);

        var clipid=Components.interfaces.nsIClipboard;              
        if (!clip) return false;
        clip.setData(trans,null,clipid.kGlobalClipboard);      
    }
};
function getRowData(keys)
{
	var rowData = "";
	for (var i in keys) {
		var selRow = jQuery("#s3list").getRowData(keys[i]);
		
		for (var col in selRow) {
			if (selRow.hasOwnProperty(col) && col!="Action") {
				rowData = rowData + " "+ selRow[col];
			}
		}
		rowData += "\n";
	}
	copyToClipboardCrossbrowser(rowData);
	if (keys.length == 1) {
		alert("This row content has been copied to clipboard.");
	} else if (keys.length > 1) {
		alert("These row contents have been copied to clipboard.");
	}
}

function resize_grid(grid) {
	var leftColumn = $("#leftColumn");
	var container = $("#rightColumn");
	var leftMargin = $("#leftMargin");
	var rightMargin = $("#rightMargin");
	
	//total height of column header, filter and table title, navigation tab, bottom space (old :165)
	var h = 138;
	var row2Height = leftColumn.height();
	
	// IE
	if ($.browser.msie) {
		grid.jqGrid('setGridWidth', container.width() - leftMargin.width() - rightMargin.width() - 13);
		h = 141;
	} else { // FireFox
		grid.jqGrid('setGridWidth', container.width() - leftMargin.width() - rightMargin.width() - 8);
	}

	if ($('#filterCriteria') && $('#filterCriteria').is(':visible')) {
		row2Height = row2Height - $('#filterCriteria').height();
		row2Height = row2Height - 11; // 11: <br> height
	}
	
	if ( $('#filterHeader')) {
		row2Height = row2Height - $('#filterHeader').height();
	}
	
	// only update row height, subtract column header, filter and table title, navigation tab
	row2Height = row2Height - h;
	$(".ui-jqgrid-bdiv").css('height', row2Height);
	$(".frozen-bdiv.ui-jqgrid-bdiv").css('height',  row2Height - 16); // 16: height of horizontal scrollbar
}
function htmlEncode(value){
    return value.replace(/[\"]/g, '&quot;')
    			.replace(/[\\]/g, '&#92;')
    			.replace(/[\=]/g, '&#61;');
}

function reSizeFilter(id,button,filterCriteria)
{
	$("#"+id).mouseover(function(){
		$("#"+id).addClass("ui-state-hover");
	});
	
	$("#"+id).mouseout(function(){
		$("#"+id).removeClass("ui-state-hover");
	});
	
	var filter = document.getElementById(filterCriteria);
	
	$("#"+id).click(function(){
		if (filter.style.display == 'none')
			{
				$("#"+button).removeClass("ui-icon-circle-triangle-s");
				$("#"+button).addClass("ui-icon-circle-triangle-n");
			}
		else
			{
				$("#"+button).removeClass("ui-icon-circle-triangle-n");
				$("#"+button).addClass("ui-icon-circle-triangle-s");
			}
		$("#"+filterCriteria).slideToggle('fast','linear');
		if ($("#s3list")) {
			resize_grid($("#s3list"));
		}
	});
}

$(document).ready(function() {
	reSizeFilter("minFilterButton","minButton","filterCriteria");
});

var defaultConfirmDialogId = "table-save-confirm";
function createConfirmDialog(boxId)
{
	if (boxId == null)
		boxId = defaultConfirmDialogId ;
	$('body').append('<div class="ui-dialog-text" id="'+boxId+'" title="Confirm" style="text-align: center;"><br/><br/><span>Are you sure?</span></div>');
}

function declareConfirmBox(excutedFunction,boxId)
{
	if (boxId == null) 
		boxId = defaultConfirmDialogId ;
	createConfirmDialog(boxId);
    $( "#"+boxId ).dialog({
        resizable: false,
        height:140,
        autoOpen: false,
        modal: true,
 		close: function() {
        	$(window).bind('resize', function() {
        		resizeMe($(window).height(), $(window).width());
        	});
        },        buttons: {
            "Ok": function() {
            	$( this ).dialog( "close" );
            	//Create the function call from function name and parameter.
            	var funcCall = excutedFunction + "();";            	 
            	//Call the function
            	var ret = eval(funcCall);
            	
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        }
    });
}

var defaultAlerDialogId = "alert-dialog";
function createAlertDialog(message,boxId)
{
	$('body').append('<div class="ui-dialog-text" id="'+boxId+'" title="Message" style="text-align: center;"><br/><br/><span>'+message+'</span></div>');
}
function declareAlertDialog(message, action, boxId)
{
	if (boxId == null) 
		boxId = defaultAlerDialogId ;
	createAlertDialog(message,boxId);
	 $( "#"+boxId ).dialog({
         modal: true,
         autoOpen: false,
		close: function() {
        	$(window).bind('resize', function() {
        		resizeMe($(window).height(), $(window).width());
        	});
        },
         buttons: {
             Ok: function() {
            	 if (action != null)
            		 {
	            		//Create the function call from function name and parameter.
	                 	var funcCall = action + "();";            	 
	                 	//Call the function
	                 	var ret = eval(funcCall);
            		 }
                 $( this ).dialog( "close" );
             }
         }
     });
}

function openAlert(boxId)
{
	if (boxId == null)
		boxId = defaultAlerDialogId;
	$( "#"+boxId ).dialog("open");
	$(window).unbind('resize');
}

function openConfirmBox(boxId)
{
	if (boxId == null)
		boxId = defaultConfirmDialogId;
	$( "#"+boxId ).dialog("open");
	 $(window).unbind('resize');
}

function increaseBoxplotTooltipRange(imgId)
{
	var resize = 2.0;
	var chart = document.getElementById(imgId);
	if (chart != null)
		{
			var useMap = chart.getAttribute("usemap");
			useMap = useMap.replace("#", "");
			// resize image map
		    var map = document.getElementById(useMap);
		    if (map != null)
		    	{
				    for (var i = 0; i < map.areas.length; i++) {
				      var area = map.areas[i];
				      var coords = area.coords.split(',');
				      for (var j = 0; j < coords.length; j++) {
				    	  if (j==1)
				    		  {
				    		  	coords[j] = parseFloat(coords[j],10) - resize;
				    		  }
				    	  else if (j==3)
				    		  {
				    		  	coords[j] = parseFloat(coords[j],10) + resize;
				    		  }
				    		  
				      }
				      var tempCoord = coords[0];
				      for (var k = 1; k< coords.length; k++)    	  
				    	  tempCoord = tempCoord + ',' + coords[k];
				      area.coords = tempCoord;
				    }
		    	}
		}
}



